import {
	ST_TOKEN
} from "@/constants/index.js";

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

function checkTel(tel) {
	if (!tel || tel.length != 11) return false;
	return /^1[3456789]\d{9}$/.test(tel.trim());
}

function dateFormat(date, fmt) {
	let ret;
	const opt = {
		"Y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"H+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"S+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt;
}

function checkEmail(email) {
	if (!email) return false;
	return /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(email.trim());
}

function checkIDCard(IDCard) {
	if (!IDCard) return false;

	IDCard = IDCard.trim();
	if (IDCard.length == 15) return false;
	if (!(IDCard.length == 18 && /\d{17}[\dxX]/.test(IDCard))) return false;

	//身份证每位数字的权重
	var RATIO = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
	//身份证末尾数字
	var REMAINDER = ["1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2"];
	var idNumArr = IDCard.split('');
	var lastValue = idNumArr[17].toLocaleLowerCase(); //最后一位数字或x
	var sum = 0;
	for (var i = 0; i < 17; i++) {
		sum += idNumArr[i] * RATIO[i];
	}
	var flag = lastValue == REMAINDER[sum % 11];
	if (!flag) return false;

	var date = strToDate(IDCard.substring(6, 10) + "-" + IDCard.substring(10, 12) + "-" + IDCard.substring(12, 14) +
		" 00:00:00");
	var end = new Date();
	var begin = strToDate("1900-01-01 00:00:00");
	var birthDate = formatDate(date, "ymd");
	var _birthDate = IDCard.substring(6, 14);


	return date < end && date > begin && birthDate == _birthDate;
}
/**
 * 字符串转时间
 * @param str
 * @returns {boolean}
 */
function strToDate(str) {
	var date = false;
	str = (str || "").trim();
	try {
		date = new Date(str);
	} catch (e) {}

	if (!date || !date.getTime()) {
		date = new Date();
		str = str.split(/\s/);
		str[0] = (str[0] || "").split(/\-/);
		str[1] = (str[1] || "").split(/:/);
		date.setFullYear(str[0][0] || 0, str[0][1] - 1, str[0][2] || 0);
		date.setHours(str[1][0] || 0, str[1][1] || 0, str[1][2] || 0);
	}
	return date;
}

/**
 * 格式化日期
 * @param ms        时间戳(以毫秒为单位)，也可以是date类型数据
 * @param format    [可选]时间格式,y:年 m:月 d:日 h:时 M:分 s:秒
 *                    默认是"y-m-d h:M:s" =>2013-01-06 17:37:31
 */
function formatDate(ms, format) {
	var _d = typeof ms == "object" ? ms : new Date(Math.floor(ms));
	var weekday = ["日", "一", "二", "三", "四", "五", "六"];

	format = format ? format : "y-m-d h:M:s";
	var _add0 = function(n) {
		return n < 10 ? "0" + n : n;
	};
	var _ = {};
	_.y = _d.getFullYear();
	_.m = _add0(_d.getMonth() + 1);
	_.d = _add0(_d.getDate());
	_.h = _add0(_d.getHours());
	_.M = _add0(_d.getMinutes());
	_.s = _add0(_d.getSeconds());

	//今，明，后
	var date = new Date();
	date.setHours(0, 0, 0, 0);
	_d.setHours(0, 0, 0, 0);
	var _t = _d.getTime() - date.getTime()
	var day = 24 * 60 * 60 * 1000
	if (0 <= _t && _t < day) {
		_.w = '今天'
	} else if (day <= _t && _t < 2 * day) {
		_.w = '明天'
	} else if (2 * day <= _t && _t < 3 * day) {
		_.w = '后天'
	} else {
		_.w = "星期" + weekday[_d.getDay()];
	}

	Object.keys(_).map(function(k) {
		format = format.replace(k, _[k]);
	});
	return format;
}

function checkLogin() {
	let token = uni.getStorageSync(ST_TOKEN);
	if (!token) {
		uni.showModal({
			title: '提示',
			content: '登陆后即可获取安全咨询',
			success: (e) => {
				if (e.confirm) {
					uni.clearStorageSync();
					uni.reLaunch({
						url: '/pages/register/login'
					})
				}
			}
		})
	}
	return !!token;
}
module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateFormat: dateFormat,
	dateUtils: dateUtils,
	checkTel: checkTel,
	checkEmail: checkEmail,
	checkIDCard: checkIDCard,
	checkLogin: checkLogin
}
